package com.coocaa.ops.plus.dashboard.v1.codegen.util;

import com.coocaa.ops.plus.dashboard.v1.codegen.constant.VmConstants;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.*;
import java.util.Properties;

/**
 * @author : bijiahao
 * @date : 2019/4/24.
 * @description:<p> </p>
 */
public class VmTemplateUtil {
    private static final Logger log = LoggerFactory.getLogger(VmTemplateUtil.class);

    private static VelocityEngine ve;
    private static Properties p;

    static {
        p = new Properties();

        p.setProperty(VmConstants.VM_LOADPATH_KEY, VmConstants.VM_LOADPATH_VALUE);
        p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "");
        p.setProperty(Velocity.ENCODING_DEFAULT, VmConstants.UTF8);
        p.setProperty(Velocity.INPUT_ENCODING, VmConstants.UTF8);
        p.setProperty("file.resource.loader.unicode", "true");
        ve = new VelocityEngine(p);
    }

    /**
     * <p>
     * 将模板转化成为文件
     * </p>
     *
     * @param context      内容对象
     * @param templatePath 模板文件
     * @param outputFile   文件生成的目录
     */
    public static void vmToFile(VelocityContext context, String templatePath, String outputFile) throws IOException {
        Assert.hasText(templatePath, "模板路径不能为空");
        try {
            Template template = ve.getTemplate(templatePath, VmConstants.UTF8);
            File file = new File(outputFile);
            if (!file.getParentFile().exists()) {
                // 如果文件所在的目录不存在，则创建目录
                if (!file.getParentFile().mkdirs()) {
                    log.debug("创建文件所在的目录失败!");
                    return;
                }
            }
            FileOutputStream fos = new FileOutputStream(outputFile);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, VmConstants.UTF8));
            template.merge(context, writer);
            writer.close();
            log.debug("模板:" + templatePath + ";  文件:" + outputFile);
        } catch (Exception e) {
           throw  new RuntimeException("加载模板文件异常: " +templatePath);
        }
    }


}
